<template>
  <view class="u-page">
    <up-form ref="pwdRef" :model="user" :rules="rules" label-width="80">
      <up-form-item label="旧密码:" prop="oldPassword">
        <up-input v-model="user.oldPassword" clearable></up-input>
      </up-form-item>
      <up-form-item label="新密码" prop="newPassword">
        <up-input type="password" v-model="user.newPassword" clearable></up-input>
      </up-form-item>
      <up-form-item label="确认密码:" prop="confirmPassword">
        <up-input type="password" v-model="user.confirmPassword" clearable></up-input>
      </up-form-item>
      <up-button type="primary" text="提交" @click="submit"></up-button>
    </up-form>
  </view>
</template>

<script lang="ts" setup>
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { to } from 'await-to-js';

const pwdRef = ref();
const user = ref({ oldPassword: '', newPassword: '', confirmPassword: '' });
const equalToPassword = (rule: any, value: string, callback: any) => {
  if (user.value.newPassword !== value) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};
const rules = ref({
  oldPassword: [
    {
      required: true,
      message: '旧密码不能为空',
      trigger: ['change', 'blur']
    }
  ],
  newPassword: [
    {
      required: true,
      message: '新密码不能为空',
      trigger: ['change', 'blur']
    },
    {
      min: 6,
      max: 20,
      message: '长度在 6 到 20 个字符',
      trigger: ['change', 'blur']
    },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      required: true,
      validator: equalToPassword,
      trigger: ['change', 'blur']
    }
  ]
});

const submit = async () => {
  pwdRef.value.validate().then(async (valid: boolean) => {
    if (valid) {
      let frompamams = {
        oldPassword: user.value.oldPassword,
        newPassword: user.value.newPassword
      };
      const [err, res] = await to(uni.$u.http.put(`/system/appUser/profile/updatePwd`, frompamams, { header: { isEncrypt: true } }));
      if (res) {
        modal.msgSuccess('修改成功');
        tab.navigateBack();
      }
    }
  });
};
</script>

<style lang="scss" scoped>



</style>
